<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/3/1
 * Time: 下午5:53
 */

namespace app\common\Model;


class UserBalance extends BaseModel
{
    public static $tab_name = 'user_balance';

    protected $resultSetType = 'collection';

    /**
     * 用户充值后更新用户余额
     * @param $uid
     * @param $amount 单位为分
     */
    public static function updateUserBalance($uid, $amount)
    {
        $model = model("app\common\Model\UserBalance");

        $res = $model->where('uid', $uid)->where('uid', $uid)->find();

        if ($res != null) {
            $model->recharge_balance = $res->recharge_balance + $amount;
            $model->where('uid', $uid);
            $model->isUpdate(true)->save();
            return $model->getData();
        }
        self::createUserWallet($uid);
        $model->recharge_balance = $res['recharge_balance'] + $amount;
        $model->where('uid', $uid);
        $model->isUpdate(true)->save();
        return $model->getData();


    }

    /**
     * 创建账户钱包
     * @param $uid
     * @return array|bool|mixed|string
     */
    public static function createUserWallet($uid)
    {
        if (empty($uid)) {
            return false;
        }
        $model = model("app\common\Model\UserBalance");
        $model->uid = $uid;
        $model->recharge_balance = 0;
        $model->withdraw_balance = 0;
        $model->frozen_balance = 0;
        if ($model->save()) {
            return $model->getData();
        }
        return $model->getError();
    }

    /**
     * @param $uid
     */
    public static function getUserBalance($uid)
    {
        $model = model("app\common\Model\UserBalance");

        $res = $model->where('uid', $uid)->where('uid', $uid)->find();
        if(!$res){
            self::createUserWallet($uid);
            $res = $model->where('uid', $uid)->where('uid', $uid)->find();
        }

        return $res->getData();
    }
}